package com.antg.service;

import com.antg.constant.SysConstant;
import com.antg.util.ParseUtil;

import java.io.*;
import java.util.*;

/**
 * @Description: 任务执行器
 * @Author 子兔Antg
 * @Date 2021/10/30
 **/
public class TaskExecutor {
    private  BufferedReader br;
    private  BufferedWriter normal_bw;
    private  BufferedWriter error_bw;
    private  BufferedWriter error_task_bw;

    private String outputPath;

    public TaskExecutor(String outputPath) {
        this.outputPath = outputPath;
    }

    //执行多个任务
    public void execute(List<String> taskList) throws IOException {
        error_task_bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputPath+SysConstant.OUTPUT_ERROR_TASK,true)));//追加模式
        error_task_bw.write("失败任务如下:\n");
        for (String ele : taskList) {
            boolean res = execute(new File(ele));
            if(!res){
                error_task_bw.write(ele);
            }
        }
        error_task_bw.close();

    }

    //执行单个任务
    public boolean execute(File task) throws IOException {
        String type = getType(task);

        if(type.equals(SysConstant.TYPE_OTHER)){
            //异常数据输出
            error_bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputPath+SysConstant.OUTPUT_OTHER,true)));//追加模式
            error_bw.write("error_file========>"+task.getAbsolutePath()+"\n");
            error_bw.close();
            return false;
        }

        return taskCore(task, type);
    }

   //依据文件内容获取文件的类型
    public  String getType(File task) throws IOException {
        if(!task.exists()||task.isDirectory()){
            return SysConstant.TYPE_OTHER;
        }
        // 输入流
        br = new BufferedReader(new InputStreamReader(new FileInputStream(task), SysConstant.CHARSET));
        //仅读取第一行参数
        String line = br.readLine();
        if(line==null){
            return SysConstant.TYPE_OTHER;
        }else if(line.startsWith("User")){
            return SysConstant.TYPE_USER;
        }else if(line.startsWith("<comment>")){
            return SysConstant.TYPE_CONTENT;
        }else {
            return SysConstant.TYPE_OTHER;
        }
    }
    //封装结果
    public StringBuilder getRes(String userId,String[] data){
        StringBuilder res = new StringBuilder();
        res.append(userId+"\t");
        boolean isFirst = true;
        for (String ele : data) {
            if(!isFirst){
                res.append("\t");
            }
            res.append(ele);
            isFirst = false;
        }
        res.append("\n");
        return res;
    }

    /**
     * 执行任务
     *  逐行读取文件并解析数据然后输出到指定目录
     *  如果是<comment>开头 那么就是微博内容
     *  如果是User开头 那么就是user内容
     *
     *
     * */
    public  boolean taskCore(File task,String type) throws IOException {
        //校验
        if(!task.exists()||task.isDirectory()){
            return false;
        }

        //根据类型决定输出的文件的地址
        String normalOutput;
        String otherOutput = outputPath+SysConstant.OUTPUT_OTHER;
        if(type.equals(SysConstant.TYPE_USER)){
            normalOutput = outputPath+SysConstant.OUTPUT_USER;
        }else{
            normalOutput = outputPath+SysConstant.OUTPUT_CONTENT;
        }

        // 输入流
        br = new BufferedReader(new InputStreamReader(new FileInputStream(task), SysConstant.CHARSET));
        // 输出流
        //正常数据输出
        normal_bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(normalOutput,true)));//追加模式
        //异常数据输出
        error_bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(otherOutput,true)));//追加模式

        //一些参数
        String line;
        StringBuilder res = new StringBuilder();//结果 使用StringBuilder可以字符串追加的提高性能,但是不是线程安全的
        StringBuilder err_res = new StringBuilder();//结果 使用StringBuilder可以字符串追加的提高性能,但是不是线程安全的
        String userId = task.getName().replace(".txt","");
        //循环读取并解析
        while((line=br.readLine())!=null){

            if(line.startsWith("User")){
                //User数据
                String[] userData = new String[0];
                try {
                    userData = ParseUtil.getUserData(line, new String[]{"remark"});
                    res.append(getRes(userId, userData));
                } catch (Exception e) {
                    err_res.append(task.getAbsolutePath()+"\t"+line+"\n");
                }
            }else if(line.startsWith("<comment>")){
                //微博数据

                String[] contentData = new String[0];
                try {
                    contentData = ParseUtil.getContentData(line, new String[]{"content","time","repostsCount","commentsCount"});
                    res.append(getRes(userId, contentData));
                } catch (Exception e) {
                    err_res.append(task.getAbsolutePath()+"\t"+line+"\n");
                }
            }else{
                //脏数据
                //记录文件的内容
                err_res.append(task.getAbsolutePath()+"\t"+line+"\n");
            }
        }
        //输出数据
        normal_bw.write(res.toString());
        error_bw.write(err_res.toString());
        //关流
        br.close();
        normal_bw.close();
        error_bw.close();
        return true;
    }
}
